package com.tianji.learning.mq;

import cn.hutool.core.util.ObjectUtil;
import com.tianji.api.dto.remark.LikedTimesDTO;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.service.IInteractionReplyService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

import static com.tianji.common.constants.MqConstants.Exchange.LIKE_RECORD_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.QA_LIKED_TIMES_KEY;
import static com.tianji.common.constants.MqConstants.Queue.QA_LIKE_TIMES_QUEUE;

/**
 * @author Administrator
 * @version 1.0
 * @description: TODO
 * @date 2024/8/26 14:51
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class LikeTimesChangeListener {
    private final IInteractionReplyService replyService;

    /**
     * 监听回复点赞次数变更消息 -> 修改回复表对应的点赞次数（Day6 - 随堂）
     *
     * @param likedTimesMsg
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = QA_LIKE_TIMES_QUEUE, durable = "true"),
            exchange = @Exchange(value = LIKE_RECORD_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = QA_LIKED_TIMES_KEY
    ))
    public void listeneReplyLikeTimesChangeMsg(List<LikedTimesDTO> likedTimesMsg) {
        // 1、消息健壮性判断
        if (!ObjectUtil.isNotEmpty(likedTimesMsg)) {
            log.error("点赞次数变更消息格式异常，消息：{}", likedTimesMsg);
            return;
        }

        // 2、根据ID更新回复对应的点赞数
        log.info("监听到点赞次数变更消息：{}", likedTimesMsg);
        List<InteractionReply> replys = new ArrayList<>(likedTimesMsg.size());
        for (LikedTimesDTO likedTimesDTO : likedTimesMsg) {
            InteractionReply reply = new InteractionReply();
            reply.setId(likedTimesDTO.getBizId());
            reply.setLikedTimes(likedTimesDTO.getLikedTimes());
            replys.add(reply);
        }
        replyService.updateBatchById(replys,100);
    }
}
